﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using PmuRegistry.Silverlight.ModalDialogs;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;

namespace PmuRegistry.Silverlight.Pages.Devices
{
	public partial class AddNew : Page
	{
		PhasorDataServiceClient m_client;
		ActivityWindow m_activityWindow;
		bool m_inEditMode = false;
		int m_deviceID = 0;
        Device m_deviceToEdit;

		public AddNew()
		{
			InitializeComponent();            
			Loaded += new RoutedEventHandler(AddNew_Loaded);
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetDevicesCompleted += new EventHandler<GetDevicesCompletedEventArgs>(client_GetDevicesCompleted);
			m_client.GetCompaniesCompleted += new EventHandler<GetCompaniesCompletedEventArgs>(client_GetCompaniesCompleted);
			m_client.GetInterconnectionsCompleted += new EventHandler<GetInterconnectionsCompletedEventArgs>(client_GetInterconnectionsCompleted);
			m_client.GetVendorDevicesCompleted += new EventHandler<GetVendorDevicesCompletedEventArgs>(client_GetVendorDevicesCompleted);
			m_client.GetProtocolsCompleted += new EventHandler<GetProtocolsCompletedEventArgs>(client_GetProtocolsCompleted);
			m_client.GetTimeZonesCompleted += new EventHandler<GetTimeZonesCompletedEventArgs>(client_GetTimeZonesCompleted);
			m_client.SaveDeviceCompleted += new EventHandler<SaveDeviceCompletedEventArgs>(client_SaveDeviceCompleted);
			m_client.GetDeviceByDeviceIDCompleted += new EventHandler<GetDeviceByDeviceIDCompletedEventArgs>(client_GetDeviceByDeviceIDCompleted);
			m_client.GetConcentratorDeviceCompleted += new EventHandler<GetConcentratorDeviceCompletedEventArgs>(client_GetConcentratorDeviceCompleted);
			m_client.GetDeviceListByParentIDCompleted += new EventHandler<GetDeviceListByParentIDCompletedEventArgs>(client_GetDeviceListByParentIDCompleted);
			m_client.GetDeviceStatusesCompleted += new EventHandler<GetDeviceStatusesCompletedEventArgs>(client_GetDeviceStatusesCompleted);
			m_client.GetTechnicalContactByCompanyCompleted += new EventHandler<GetTechnicalContactByCompanyCompletedEventArgs>(client_GetTechnicalContactByCompanyCompleted);
            m_client.GetFundingSourcesCompleted += new EventHandler<GetFundingSourcesCompletedEventArgs>(m_client_GetFundingSourcesCompleted);
			ComboboxCompany.SelectionChanged += new SelectionChangedEventHandler(ComboboxCompany_SelectionChanged);
			ButtonSave.Click += new RoutedEventHandler(ButtonSave_Click);
			ButtonClear.Click += new RoutedEventHandler(ButtonClear_Click);
			ButtonView.Click += new RoutedEventHandler(ButtonView_Click);
			ComboboxParent.SelectionChanged += new SelectionChangedEventHandler(ComboboxParent_SelectionChanged);			
		}

        void m_client_GetFundingSourcesCompleted(object sender, GetFundingSourcesCompletedEventArgs e)
        {
            if (e.Error == null)
                ComboboxFundingSource.ItemsSource = e.Result;
            else
            {
                SystemMessages sm;
                if (e.Error is FaultException<CustomServiceFault>)
                {
                    FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
                    sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                }
                else
                    sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Funding Sources", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);

                sm.Show();
            }

            if (ComboboxFundingSource.Items.Count > 0)
                ComboboxFundingSource.SelectedIndex = 0;

            if (m_deviceToEdit != null && m_deviceToEdit.FundingSourceID.HasValue)
                ComboboxFundingSource.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.FundingSourceID, m_deviceToEdit.FundingSourceName);
        }

		void ComboboxCompany_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			m_client.GetTechnicalContactByCompanyAsync(((KeyValuePair<int, string>)ComboboxCompany.SelectedItem).Key, true);
		}

		void client_GetTechnicalContactByCompanyCompleted(object sender, GetTechnicalContactByCompanyCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxTechnicalContact.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Technical Contacts By Company", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}

			if (ComboboxTechnicalContact.Items.Count > 0)
				ComboboxTechnicalContact.SelectedIndex = 0;

            if (m_deviceToEdit != null && m_deviceToEdit.TechnicalContactID.HasValue)
                ComboboxTechnicalContact.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.TechnicalContactID, m_deviceToEdit.ContactFullName);
		}

		void client_GetDeviceStatusesCompleted(object sender, GetDeviceStatusesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxStatus.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Device Statuses", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}

			if (ComboboxStatus.Items.Count > 0)
				ComboboxStatus.SelectedIndex = 0;

            if(m_deviceToEdit != null)
                ComboboxStatus.SelectedItem = new KeyValuePair<int, string>(m_deviceToEdit.StatusID, m_deviceToEdit.DeviceStatusName);
		}

		void client_GetDeviceListByParentIDCompleted(object sender, GetDeviceListByParentIDCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxDeviceList.ItemsSource = e.Result;			
		}
		
        void ButtonView_Click(object sender, RoutedEventArgs e)
		{
			if (((KeyValuePair<int, string>)ComboboxParent.SelectedItem).Key != 0)
				NavigationService.Navigate(new Uri("/Pages/Devices/AddNew.xaml?did=" + ((KeyValuePair<int, string>)ComboboxParent.SelectedItem).Key.ToString(), UriKind.Relative));
		}
		
        void client_GetConcentratorDeviceCompleted(object sender, GetConcentratorDeviceCompletedEventArgs e)
		{
			if (e.Error == null && e.Result != null)
			{
                Device device = new Device();
                device = e.Result;
                ToolTip toolTip = new ToolTip();
                toolTip.DataContext = device;
                toolTip.Template = Application.Current.Resources["PdcInfoToolTipTemplate"] as ControlTemplate;
                ToolTipService.SetToolTip(ButtonView, toolTip);
			}
		}
		
        void ComboboxParent_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (((KeyValuePair<int, string>)ComboboxParent.SelectedItem).Key != 0)
				m_client.GetConcentratorDeviceAsync(((KeyValuePair<int, string>)ComboboxParent.SelectedItem).Key);
		}
		
        void client_GetDeviceByDeviceIDCompleted(object sender, GetDeviceByDeviceIDCompletedEventArgs e)
		{
			//System.Threading.Thread.Sleep(5000);
            m_deviceToEdit = new Device();
			if (e.Error == null)
			{
                m_deviceToEdit = e.Result;
                GridDeviceDetail.DataContext = m_deviceToEdit;

                if (ComboboxCompany.Items.Count > 0)
                    ComboboxCompany.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.CompanyID, m_deviceToEdit.CompanyName);
                
                if (ComboboxInterconnection.Items.Count > 0)
                    ComboboxInterconnection.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.InterconnectionID, m_deviceToEdit.InterconnectionName);
                
                if (ComboboxStatus.Items.Count > 0)
                    ComboboxStatus.SelectedItem = new KeyValuePair<int, string>(m_deviceToEdit.StatusID, m_deviceToEdit.DeviceStatusName);
                
                if (m_deviceToEdit.TechnicalContactID.HasValue)
                    ComboboxTechnicalContact.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.TechnicalContactID, m_deviceToEdit.ContactFullName);
				else if (ComboboxTechnicalContact.Items.Count > 0)
					ComboboxTechnicalContact.SelectedIndex = 0;
                
                if (m_deviceToEdit.ParentID.HasValue)
                    ComboboxParent.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.ParentID, m_deviceToEdit.ParentAcronym);
				else if (ComboboxParent.Items.Count > 0)
					ComboboxParent.SelectedIndex = 0;
                
                if (m_deviceToEdit.ProtocolID.HasValue)
                    ComboboxProtocol.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.ProtocolID, m_deviceToEdit.ProtocolName);
				else if (ComboboxProtocol.Items.Count > 0)
					ComboboxProtocol.SelectedIndex = 0;
                
                if (string.IsNullOrEmpty(m_deviceToEdit.TimeZone))
					ComboboxTimeZone.SelectedIndex = 0;
				else if (ComboboxTimeZone.Items.Count > 0)
                    ComboboxTimeZone.SelectedItem = m_deviceToEdit.TimeZone;
                
                if (m_deviceToEdit.VendorDeviceID.HasValue)
                    ComboboxVendorDevice.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.VendorDeviceID, m_deviceToEdit.VendorDeviceName);
				else if (ComboboxVendorDevice.Items.Count > 0)
					ComboboxVendorDevice.SelectedIndex = 0;
                
                if (m_deviceToEdit.FundingSourceID.HasValue)
                    ComboboxFundingSource.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.FundingSourceID, m_deviceToEdit.FundingSourceName);
                else if (ComboboxFundingSource.Items.Count > 0)
                    ComboboxFundingSource.SelectedIndex = 0;

                if (m_deviceToEdit.IsConcentrator)	//then display list of devices.
				{
                    m_client.GetDeviceListByParentIDAsync(m_deviceToEdit.ID);
					StackPanelDeviceList.Visibility = Visibility.Visible;
					StackPanelPhasorsMeassurements.Visibility = Visibility.Collapsed;
                    TextBlockTitle.Text = "Devices For Concentrator: " + m_deviceToEdit.Acronym;
				}
				else
				{
					StackPanelPhasorsMeassurements.Visibility = Visibility.Visible;
					StackPanelDeviceList.Visibility = Visibility.Collapsed;
				}
			}
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Device Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (m_activityWindow != null)
				m_activityWindow.Close();
		}
		
        void client_SaveDeviceCompleted(object sender, SaveDeviceCompletedEventArgs e)
		{
			SystemMessages sm;
			if (e.Error == null)
			{
				ClearForm();
				sm = new SystemMessages(new Message() { UserMessage = e.Result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
						ButtonType.OkOnly);
			}
			else
			{
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Device Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
			}
			sm.Show();

			NavigationService.Navigate(new Uri("/Pages/Devices/Browse.xaml", UriKind.Relative));
		}
		
        void ButtonClear_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonClearTransform);
			sb.Begin();
			ClearForm();
		}
		
        void ButtonSave_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonSaveTransform);
			sb.Begin();
            
            if (IsValid())
            {
                Device device = new Device();
                device.ParentID = ((KeyValuePair<int, string>)ComboboxParent.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboboxParent.SelectedItem).Key;
                device.Acronym = TextBoxAcronym.Text.CleanText();
                device.Name = TextBoxName.Text.CleanText();
                device.SubstationAcronym = TextBoxSubstationAcronym.Text.CleanText();
                device.SubstationName = TextBoxSubstationName.Text.CleanText();
                device.Longitude = TextBoxLongitude.Text.ToNullableDecimal(); //string.IsNullOrEmpty(TextBoxLongitude.Text) ? (decimal?)null : Convert.ToDecimal(TextBoxLongitude.Text);
                device.Latitude = TextBoxLatitude.Text.ToNullableDecimal(); //string.IsNullOrEmpty(TextBoxLatitude.Text) ? (decimal?)null : Convert.ToDecimal(TextBoxLatitude.Text);
                device.TimeZone = ((KeyValuePair<string, string>)ComboboxTimeZone.SelectedItem).Key;
                device.InterconnectionID = ((KeyValuePair<int, string>)ComboboxInterconnection.SelectedItem).Key;
                device.CompanyID = ((KeyValuePair<int, string>)ComboboxCompany.SelectedItem).Key;
                device.VendorDeviceID = ((KeyValuePair<int, string>)ComboboxVendorDevice.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboboxVendorDevice.SelectedItem).Key;
                device.ProtocolID = ((KeyValuePair<int, string>)ComboboxProtocol.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboboxProtocol.SelectedItem).Key;
                device.MeasuredLines = TextBoxMeasuredLines.Text.ToInteger(); //string.IsNullOrEmpty(TextBoxMeasuredLines.Text) ? 1 : Convert.ToInt32(TextBoxMeasuredLines.Text);
                device.IsConcentrator = (bool)CheckboxConcentrator.IsChecked;
                device.StatusID = ((KeyValuePair<int, string>)ComboboxStatus.SelectedItem).Key;
                device.StatusDate = DateTime.Now;
                device.TechnicalContactID = ((KeyValuePair<int, string>)ComboboxTechnicalContact.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboboxTechnicalContact.SelectedItem).Key;
                device.InServiceDate = null;
                device.FundingSourceID = ((KeyValuePair<int, string>)ComboboxFundingSource.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboboxFundingSource.SelectedItem).Key;

                if (m_inEditMode == false && m_deviceID == 0)
                    m_client.SaveDeviceAsync(device, true, 0, 0);
                else
                {
                    device.ID = m_deviceID;
                    m_client.SaveDeviceAsync(device, false, 0, 0);
                }
            }
		}

        bool IsValid()
        {
            bool isValid = true;
            
            if (string.IsNullOrEmpty(TextBoxAcronym.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Acronym", SystemMessage = "Please provide valid Acronym for a device.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxAcronym.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxName.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Name", SystemMessage = "Please provide valid Name for a device.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                    {
                                                        TextBoxName.Focus();
                                                    });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxSubstationAcronym.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Substation Acronym", SystemMessage = "Please provide valid Substation Acronym for a device.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxSubstationAcronym.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (!TextBoxMeasuredLines.Text.IsInteger())
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Measured Lines", SystemMessage = "Please provide valid integer value for Measured Lines.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxMeasuredLines.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            return isValid;
        }

        void client_GetTimeZonesCompleted(object sender, GetTimeZonesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxTimeZone.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Time Zones", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxTimeZone.Items.Count > 0)
				ComboboxTimeZone.SelectedIndex = 0;

            if (m_deviceToEdit != null && !string.IsNullOrEmpty(m_deviceToEdit.TimeZone))
                ComboboxTimeZone.SelectedItem = m_deviceToEdit.TimeZone;
		}
		
        void client_GetProtocolsCompleted(object sender, GetProtocolsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxProtocol.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Protocols", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxProtocol.Items.Count > 0)
				ComboboxProtocol.SelectedIndex = 0;

            if (m_deviceToEdit != null && m_deviceToEdit.ProtocolID.HasValue)
                ComboboxProtocol.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.ProtocolID, m_deviceToEdit.ProtocolName);
		}
		
        void client_GetVendorDevicesCompleted(object sender, GetVendorDevicesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxVendorDevice.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Vendor Devices", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxVendorDevice.Items.Count > 0)
				ComboboxVendorDevice.SelectedIndex = 0;

            if (m_deviceToEdit != null && m_deviceToEdit.VendorDeviceID.HasValue)
                ComboboxVendorDevice.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.VendorDeviceID, m_deviceToEdit.VendorDeviceName);
		}
		
        void client_GetInterconnectionsCompleted(object sender, GetInterconnectionsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxInterconnection.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Interconnections", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxInterconnection.Items.Count > 0)
				ComboboxInterconnection.SelectedIndex = 0;

            if (m_deviceToEdit != null)
                ComboboxInterconnection.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.InterconnectionID, m_deviceToEdit.InterconnectionName);
		}
				
		void client_GetCompaniesCompleted(object sender, GetCompaniesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxCompany.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Companies", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxCompany.Items.Count > 0)
				ComboboxCompany.SelectedIndex = 0;
		    
            if (m_deviceToEdit != null)
                ComboboxCompany.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.CompanyID, m_deviceToEdit.CompanyName);
        }
		
        void client_GetDevicesCompleted(object sender, GetDevicesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxParent.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Devices", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxParent.Items.Count > 0)
				ComboboxParent.SelectedIndex = 0;

            if (m_deviceToEdit != null)
                ComboboxParent.SelectedItem = new KeyValuePair<int, string>((int)m_deviceToEdit.ParentID, m_deviceToEdit.ParentAcronym);
		}
		
        void AddNew_Loaded(object sender, RoutedEventArgs e)
		{
			StackPanelDeviceList.Visibility = Visibility.Collapsed;
			if (this.NavigationContext.QueryString.ContainsKey("did"))
			{
				m_activityWindow = new ActivityWindow("Loading Data... Please Wait...");
				m_activityWindow.Show();
				m_deviceID = Convert.ToInt32(this.NavigationContext.QueryString["did"]);
				m_inEditMode = true;
                //System.Threading.Thread.Sleep(3000);
				m_client.GetDeviceByDeviceIDAsync(m_deviceID);
			}			
		}
		
        void ClearForm()
		{
			GridDeviceDetail.DataContext = new Device();
			ComboboxCompany.SelectedIndex = 0;			
			ComboboxInterconnection.SelectedIndex = 0;			
			ComboboxParent.SelectedIndex = 0;
			ComboboxProtocol.SelectedIndex = 0;
			ComboboxTimeZone.SelectedIndex = 0;
			ComboboxVendorDevice.SelectedIndex = 0;
			ComboboxStatus.SelectedIndex = 0;
			ComboboxTechnicalContact.SelectedIndex = 0;
			m_inEditMode = false;
			m_deviceID = 0;
		}

		// Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			StackPanelPhasorsMeassurements.Visibility = Visibility.Collapsed;
            m_client.GetTimeZonesAsync(true);
            m_client.GetDevicesAsync(DeviceType.Concentrator, true);
			m_client.GetCompaniesAsync(false);
			m_client.GetInterconnectionsAsync(false);
			m_client.GetVendorDevicesAsync(true);
			m_client.GetProtocolsAsync(true);			
			m_client.GetDeviceStatusesAsync();
			m_client.GetTechnicalContactByCompanyAsync(0, true);
            m_client.GetFundingSourcesAsync(true);
		}

		private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
		{
			string deviceId = ((HyperlinkButton)sender).Tag.ToString();
			NavigationService.Navigate(new Uri("/Pages/Devices/AddNew.xaml?did=" + deviceId, UriKind.Relative));
		}

		private void HyperlinkButtonPhasors_Click(object sender, RoutedEventArgs e)
		{
			int deviceId = Convert.ToInt32(((HyperlinkButton)sender).Tag.ToString());
			string acronym = ToolTipService.GetToolTip((HyperlinkButton)sender).ToString();
			Phasors phasors = new Phasors(deviceId, acronym);
			phasors.Show();
		}

		private void HyperlinkButtonMeasurements_Click(object sender, RoutedEventArgs e)
		{
			string deviceId = ((HyperlinkButton)sender).Tag.ToString();
			NavigationService.Navigate(new Uri("/Pages/Manage/Measurements.xaml?did=" + deviceId, UriKind.Relative));
		}

	}
}
